package com.bbzn.device.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.constant.MongoDbConstant;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.dataobject.DeviceConnectLog;
import com.bbzn.device.client.dto.ct.response.OnlineOfflineNotify;
import com.bbzn.device.client.service.CwtingMessageStrategy;
import com.bbzn.device.client.service.DeviceService;
import com.bbzn.device.client.service.SimpleMongoService;
import com.bbzn.device.client.utils.OrderNoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author wulongbo
 * @Date 2021/9/22 10:27
 * @Version 1.0
 */

@Component
@Slf4j
public class DevOnOfflineReportStrategy implements CwtingMessageStrategy {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SimpleMongoService simpleMongoService;

    @Override
    public void pushMessage(JSONObject jsonObject) {
        OnlineOfflineNotify notify = JSONObject.toJavaObject(jsonObject, OnlineOfflineNotify.class);
        /**
         * 上线：1，下线：0
         */
        int state = notify.getEventType();
        if (state == 1) {
            log.info("在线========================");
            state = 1;
        } else if (state == 0) {
            log.info("离线========================");
            state = 2;
        }

        Device device = new Device();
        // state --is_online --状态 ( 0 离线 1 在线  2 未激活）
        device.setState(state);
        device.setImei(notify.getImei());
        device.setClientId(notify.getDeviceId());
        device.setConnectedAt(new Date(notify.getTimestamp()));
        deviceService.insertOrUpdateSelective(device);

        // 记录连接日志
        DeviceConnectLog log = new DeviceConnectLog();
        log.setClientid(notify.getDeviceId());
        // 0 其他 1 上线 2 下线 3 订阅 4 取消订阅
//        log.setCreateAt(System.currentTimeMillis());
        log.setCreateTime(System.currentTimeMillis());
        log.setAction(state);
        log.setId(OrderNoUtil.getOrderNo());
        simpleMongoService.insert(log, MongoDbConstant.DEVICE_CONNECT_LOG);

    }
}
